package labrom.usage.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import labrom.usage.shared.Udi;


public class ApiV1Servlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ApiV1Path path = new ApiV1Path(req.getPathInfo());
		
		if("ask".equals(path.resource)) {
			UUID guid = path.clientGuid;
			
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query q = pm.newQuery(Udi.class);
			q.declareParameters("long msb, long lsb");
			q.setFilter("guidMsb == msb && guidLsb == lsb");
			q.setOrdering("timestamp desc");
			q.setRange(0, 1);
			
			long ts = 0;
			try {
				@SuppressWarnings("unchecked")
				List<Udi> result = (List<Udi>)q.execute(guid.getMostSignificantBits(), guid.getLeastSignificantBits());
				if(result != null && !result.isEmpty())
					ts = result.get(0).getTimestamp();
			} catch(Exception e) {
				// TODO Logging?
			} finally {
				q.closeAll();
			}
			
			PrintWriter writer = resp.getWriter();
			writer.write(String.valueOf(ts));
			writer.close();
		} else {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)	throws ServletException, IOException {
		ApiV1Path path = new ApiV1Path(req.getPathInfo());
		
		if("udis".equals(path.resource)) {
			InputStream in = req.getInputStream();
			UdiPayload udis = UdiPayload.parse(in);
			udis.setAppVersionAndClientGuid(path.appVersion, path.clientGuid);
			in.close();
			
			PersistenceManager pm = PMF.get().getPersistenceManager();
			boolean success = false;
			try {
				pm.makePersistentAll(udis);
				success = true;
			} catch(Exception e) {
				// FIXME Logging?
			} finally {
				pm.close();
			}
			
			
			PrintWriter writer = resp.getWriter();
			writer.write(success ? String.valueOf(udis.size()) : "0");
			writer.close();
		} else {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
	}
	
	
	
	
	
	

}
